<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-input
          placeholder="请把你需要转换的内容粘贴在这里"
          type="textarea"
          :rows="15"
          resize="none"
          v-model="input"
          clearable>
        </el-input>
      </el-col>
      <el-col :span="12">
        <el-input
          placeholder="转换后的结果"
          type="textarea"
          :rows="15"
          resize="none"
          v-model="result"
          clearable>
        </el-input>
      </el-col>
    </el-row>
    <el-row style="float: right; margin-top: 10px">
      <el-button type="primary" @click="AsciiToUnicode">ASCII 转 Unicode</el-button>
      <el-button type="warning" @click="UnicodeToAscii">Unicode 转 ASCII</el-button>
      <el-button type="primary" @click="UnicodeToChi">Unicode 转 中文</el-button>
      <el-button type="warning" @click="ChiToUnicode">中文 转 Unicode</el-button>
      <el-button type="info" @click="reset">清空结果</el-button>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'Unicode',
  data () {
    return {
      input: '',
      result: ''
    }
  },
  methods: {
    // ASCII 转换 Unicode
    AsciiToUnicode () {
      if (!this.input) {
        this.openAlert('文本框不能为空')
      }
      let result = ''
      for (let i = 0; i < this.input.length; i++) {
        result += '&#' + this.input.charCodeAt(i) + ';'
      }
      this.result = result
    },
    // Unicode 转换 ASCII
    UnicodeToAscii () {
      if (!this.input) {
        this.openAlert('文本框不能为空')
        return
      }
      let code = this.input.match(/&#(\d+);/g)
      if (!code) {
        this.openAlert('没有合法的Unicode代码')
        return
      }
      console.log(1111)
      let result = ''
      for (let i = 0; i < code.length; i++) {
        result += String.fromCharCode(code[i].replace(/[&#;]/g, ''))
      }
      this.result = result
    },
    UnicodeToChi () {
      if (!this.input) {
        this.openAlert('文本框不能为空')
        return
      }
      let result = unescape(this.input.replace(/\\/g, '%'))
      this.result = result
    },
    ChiToUnicode () {
      if (!this.input) {
        this.openAlert('文本框不能为空')
        return
      }
      let res = []
      for (let i = 0; i < this.input.length; i++) {
        res[i] = ('00' + this.input.charCodeAt(i).toString(16)).slice(-4)
      }
      this.result = '\\u' + res.join('\\u')
    },
    reset () {
      this.input = ''
      this.result = ''
    },
    // 弹框提示
    openAlert (msg) {
      this.$alert(msg, '错误提示', {
        confirmButtonText: '确定',
        callback: action => {}
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-input {
  padding: 10px
}
</style>
